package cn.wolfcode.shop;

import cn.wolfcode.shop.domain.Catalog;
import cn.wolfcode.shop.service.ICataLogService;
import cn.wolfcode.shop.vo.JSONResultVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class CataLogController {
    @Reference
    private ICataLogService cataLogService;

    @RequestMapping("/main")
    public String mainPage(){
        return "main";
    }

    @RequestMapping("/index")
    public String indexPage(){
        return "index";
    }

    @RequestMapping("/catalog")
    public String cataLogPage(Model model){
        String allCatalogJson = cataLogService.SelectAllCache();
        model.addAttribute("allCatalogJson", allCatalogJson);
        return "catalog/catalog";
    }

    @RequestMapping("/catalog/getChildCatalog")
    public String getChildCatalog(Long catalogId, Model model){
        List<Catalog> list = cataLogService.getChildCatalog(catalogId);
        model.addAttribute("catalogList", list);
        return "catalog/child_catalog";
    }

    /**
     * 排序更新
     * @param ids
     * @return
     */
    @RequestMapping("/catalog/updateSort")
    @ResponseBody
    public JSONResultVo updateSort(@RequestBody Long[] ids){
        JSONResultVo vo = new JSONResultVo();
        try {
            cataLogService.updateSort(ids);
        } catch (Exception e){
            e.printStackTrace();
            vo.setErrorMsg(e.getMessage());
        }
        return vo;
    }

    @RequestMapping("/catalog/save")
    @ResponseBody
    public JSONResultVo saveOrUpdate(Catalog catalog){
        JSONResultVo vo = new JSONResultVo();
        try {
            cataLogService.saveOrUpdate(catalog);
        } catch (Exception e){
            e.printStackTrace();
            vo.setErrorMsg(e.getMessage());
        }
        return vo;
    }

    @RequestMapping("/catalog/delete")
    @ResponseBody
    public JSONResultVo delete(Long catalogId){
        JSONResultVo vo = new JSONResultVo();
        try {
            cataLogService.delete(catalogId);
        } catch (Exception e){
            e.printStackTrace();
            vo.setErrorMsg(e.getMessage());
        }
        return vo;
    }

}
